package com.jc.demo.helleworld;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;

import java.util.Properties;

/**
 * 测试时可以在命令行执行以下命令进行消费测试：
 * kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic my-topic --from-beginning
 */
public class HelloWorldProducer {

    public static void main(String[] args) {
        Properties props = new Properties();
        props.put("bootstrap.servers", "kafka-vm1.c7.local.jevoncode.com:9092,kafka-vm2.c7.local.jevoncode.com:9092,kafka-vm3.c7.local.jevoncode.com:9092");
        props.put("acks", "all"); //会阻塞直至全部记录提交，会比较慢些
        props.put("retries", 0);  //发送失败不重试
        props.put("batch.size", 16384); //未发送记录的缓存，每个active partition一个缓存
        props.put("linger.ms", 1);  //就算缓存还有空间，默认还是会立即发送缓存的记录，为了减少请求次数，可以设置linger.ms，如每隔1ms才发送
        props.put("buffer.memory", 33554432);   //此参数控制producer的缓存，缓存慢了之后，send方法调用就会阻塞
        props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

        Producer<String, String> producer = new KafkaProducer<>(props);
        for (int i = 0; i < 100; i++)
            producer.send(new ProducerRecord<String, String>("my-topic", Integer.toString(i), Integer.toString(i)));  //异步发送

        producer.close();
    }
}
